#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
遥测数据路由层

提供遥测数据相关的API接口：
1. 遥测数据查询和统计
2. 设备状态监控
3. 数据导出功能
4. WebSocket实时推送（遥测数据）

注意：数据大屏相关接口已迁移到 dashboard_router.py
"""
from datetime import timedelta

from fastapi import APIRouter, Depends

from app.common.auth import RequireTelemetryView
from app.common.common import PaginationDep, DbDep, TelemetryServiceDep, AuditLogDep
from app.schemas.telemetry_schemas import (
	TelemetryListRequest,
	TelemetryListResponse
)
from app.schemas.user_schemas import UserInDB
from common.logger import create_logger
from common.response import ApiResponse

logger = create_logger(__name__)

router = APIRouter(prefix="/telemetry", tags=["遥测数据"])


# ==================== 遥测数据接口 ====================

@router.get(
	"/meter",
	response_model=ApiResponse[TelemetryListResponse],
	summary="获取电表遥测数据列表"
)
async def list_telemetry(
		db: DbDep,
		page: PaginationDep,
		service: TelemetryServiceDep,
		_audit: AuditLogDep,
		query: TelemetryListRequest = Depends(),
		_: UserInDB = Depends(RequireTelemetryView),
) -> ApiResponse[TelemetryListResponse]:
	"""获取电表遥测数据列表"""
	try:
		logger.info(f"查询遥测数据，参数: {query.model_dump()}")
		# 处理start_time：减去5秒
		if query.start_time:
			query.start_time -= timedelta(seconds=5)

		if query.is_init == 'Y':
			query.start_time -= timedelta(minutes=60)
			page.size = 20

		result = await service.get_paged_list(db, query, page)

		logger.info(f"遥测数据查询成功，返回 {len(result.items)} 条记录")
		return ApiResponse.success(result, "遥测数据获取成功")

	except Exception as e:
		logger.error(f"查询遥测数据失败: {e}")
		return ApiResponse.error("查询遥测数据失败", code=500)
